//
//  CourseCenterInfoViewController.m
//  xpkc
//
//  Created by TopSageOSX on 14/12/19.
//  Copyright (c) 2014年 wanmeizty. All rights reserved.
//

#import "CourseCenterInfoViewController.h"
#import "FMDatabase.h"
#import "CartModel.h"
#import "protocolViewController.h"
@interface CourseCenterInfoViewController (){
    CourseCenterInfoView *_infoView;
    NSArray *dataArray;
    //大图地址
    NSString *_lecturePicURL;
    NSString * lectureName;
    NSString *discountPrice;
    NSMutableArray * _payArray;
    NSString * downStudycard;
}

@end

@implementation CourseCenterInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _payArray=[NSMutableArray array];
    self.title = @"课程详情";
    
    if (IsIOS8) {
        //FIXME:滑动隐藏导航栏，暂时无需
        //        self.navigationController.hidesBarsOnSwipe = YES;
    }
    [self creatInfoView];
    [self getCourseInfoData];
    
    if ([UserMessage sharedUserMessage].isLogin){
    [self getStudycard];
    }
    
}

#pragma mark == creat view ==
- (void)creatInfoView{
    _infoView = [[CourseCenterInfoView alloc]initWithFrame:self.view.bounds];
    _infoView.delegate = self;
    [_infoView.buyBtn addTarget:self action:@selector(buy) forControlEvents:UIControlEventTouchUpInside];
    [_infoView.addButton addTarget:self action:@selector(add) forControlEvents:(UIControlEventTouchUpInside)];
    [_infoView.agreementBtn addTarget:self action:@selector(showAgreement) forControlEvents:UIControlEventTouchUpInside];
    [_infoView.courseImg setImageWithURL:[NSURL URLWithString:_lecturePicURL]];
    [self.view addSubview:_infoView];
}

#pragma mark -
#pragma mark == func ==
- (void)getCourseInfoData{
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"加载中";
    
    dataArray = [[NSArray alloc]init];
    //FIXME:获取课程详情
    NSString *module = @"courseBuy";
    NSString *interface = @"coursedetail";
    
    NSString *timeString = [GetTime getTime];
    NSString *hashString = [[NSString stringWithFormat:@"%@/%@/key/%@/time/%@",module,interface,KEY,timeString] md5];
    NSString *urlString = [NSString stringWithFormat:@"%@/laravel/public/%@/%@/hash/%@/appid/1",URL2,module,interface,hashString];
    
    NSDictionary *parameter = @{@"time":timeString,@"aid":self.courseId};
    
    
//    NSLog(@"--------%@-------",self.courseId);
    
    //POST请求
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
    
    [manager POST:urlString parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        
        [hud hide:YES];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        //获取列表数据
        NSDictionary *infoDic = [dic objectForKey:@"info"];
        
        //顶部图片
        [_infoView.courseImg setImageWithURL:[NSURL URLWithString:self.litpic]];
        //原价
        NSString *originalPrice = [infoDic objectForKey:@"originalPrice"];
        _infoView.originalPrice = originalPrice;
        //折扣价
        discountPrice = [infoDic objectForKey:@"discountPrice"];
        _infoView.discountPrice = discountPrice;
        
        //有效期
        if ([[infoDic objectForKey:@"validTerm"]isKindOfClass:[NSNull class]]) {
        }else{
            NSString *validTerm = [infoDic objectForKey:@"validTerm"];
            _infoView.validTerm = validTerm;
        }
        
        //简介
        NSString *introduction = [infoDic objectForKey:@"introduction"];
        // logdebug(@"%@",introduction);
        _infoView.courseIntroduction = introduction;
        //目录
        if ([[infoDic objectForKey:@"catalog"]isKindOfClass:[NSString class]]) {
        }else{
        NSArray *catalogarray = [infoDic objectForKey:@"catalog"];
        for (NSDictionary *dic in catalogarray) {
            lectureName=[dic objectForKey:@"lectureName"];
        }
        
        _infoView.catalogArray = catalogarray;
        }
        //讲师
        NSArray *teachermsg = [infoDic objectForKey:@"teacherMsg"];
        _infoView.teacherArray = teachermsg;
        //评价
        NSArray *evaluation = [infoDic objectForKey:@"evaluation"];
        _infoView.evaluationArray = evaluation;
        
        [_infoView setValueForInfoView];
        
        
        CartModel * model =[[CartModel alloc] init];
        model.price=discountPrice;
        model.title=self.titleString;
        model.gold=[NSString stringWithFormat:@"%@",[infoDic objectForKey:@"credits"]];
        model.quanID=[NSString stringWithFormat:@"%@",self.courseId];
        [_payArray addObject:model];
        
        
    }
          failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             
              logdebug(@"%@",error.localizedDescription);
              [hud hide:YES];
          }];
    
//    [self creatInfoView];
}
/**
 *  协议界面
 */
- (void)showAgreement{
    logdebug(@"显示协议");
  
//    NSLog(@"%@",self.courseId);
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"加载中";
    
    NSString *module = @"courseBuy";
    NSString *interface = @"coursedetail";
    
    NSString *timeString = [GetTime getTime];
    NSString *hashString = [[NSString stringWithFormat:@"%@/%@/key/%@/time/%@",module,interface,KEY,timeString] md5];
    NSString *urlString = [NSString stringWithFormat:@"%@/laravel/public/%@/%@/hash/%@/appid/1",URL2,module,interface,hashString];
    
    NSDictionary *parameter = @{@"time":timeString,@"aid":self.courseId};
    //POST请求
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:urlString parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary *dic1 = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if ([[dic1 objectForKey:@"succ"] isEqualToNumber:@1]) {
          NSDictionary * dic2 =[dic1 objectForKey:@"info"];
            NSString * str =[dic2 objectForKey:@"protocol"];
           
            if (str.length==0||str==NULL) {
                ShowAlertMsg(@"该课程没有协议");
            }else{
                
                protocolViewController *protocol =[[protocolViewController alloc] init];
                protocol.protocolURL=str;
                [self.navigationController pushViewController:protocol animated:YES];
            }
        
        }
        [hud hide:YES];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
       
        [hud hide:YES];
    }];

    
    
    
    
}
- (void)listenTestWithSpark:(NSString *)spark andVideoName:(NSString *)name{
    DWCustomPlayerViewController *DCPVC = [[DWCustomPlayerViewController alloc]init];
    DCPVC.videoId = spark;
    DCPVC.videoName = name;
    DCPVC.drm = 0;
    DCPVC.playerReturn = ^(NSInteger num){
        
    };
    [self presentViewController:DCPVC animated:YES completion:^{
        
    }];
}
-(void)add
{

    if (![UserMessage sharedUserMessage].isLogin) {
        [self showAlertWithMessage:@"请先登陆"];
    }else{
       
        NSString *module = @"shopcar";
        NSString *interface = @"joinshopcart";
        
        NSString *timeString = [GetTime getTime];
        NSString *hashString = [[NSString stringWithFormat:@"%@/%@/key/%@/time/%@",module,interface,KEY,timeString] md5];
        NSString *urlString = [NSString stringWithFormat:@"%@/laravel/public/%@/%@/hash/%@/appid/1",URL2,module,interface,hashString];
        
        NSDictionary *parameter = @{@"time":timeString,@"mid":[UserMessage sharedUserMessage].userMid,@"aid":self.courseId};
        NSLog(@"%@",parameter);
        //POST请求
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        [manager POST:urlString parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
            
            ShowAlertMsg([dic objectForKey:@"msg"]);
//            CourseCenterCartViewController *CCCVC = [[CourseCenterCartViewController alloc]init];
//            
//            CCCVC.hidesBottomBarWhenPushed = YES;
//            if (IsIOS7) {
//                if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
//                    self.navigationController.interactivePopGestureRecognizer.delegate = nil;
//                }
//            }
//            [self.navigationController setNavigationBarHidden:NO animated:NO];
//            [self.navigationController pushViewController:CCCVC animated:YES];
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            
        }];

        
    }
    
}
- (void)showAlertWithMessage:(NSString *)message {
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:message delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    [alertView show];
}
- (void)buy{
    logdebug(@"buybuybuybuybuybuybuybuybuybuybuy");
    
    if (![UserMessage sharedUserMessage].isLogin) {
        [self showAlertWithMessage:@"请先登陆"];
    }else{
        CourseCenterOrderViewController *CCOVC = [[CourseCenterOrderViewController alloc]init];
        CCOVC.cartArray=_payArray;
        CCOVC.currenPrice = [discountPrice doubleValue];
        CCOVC.downStudycard=downStudycard;
        
        NSLog(@"%@",CCOVC.downStudycard);
        [self.navigationController pushViewController:CCOVC animated:YES];
        
    }
}
//获取学习卡金额 传入下一个页面
-(void)getStudycard
{
    
    NSString *module = @"shopcar";
    NSString *interface = @"studycard";
    
    NSString *timeString = [GetTime getTime];
    NSString *hashString = [[NSString stringWithFormat:@"%@/%@/key/%@/time/%@",module,interface,KEY,timeString] md5];
    NSString *urlString = [NSString stringWithFormat:@"%@/laravel/public/%@/%@/hash/%@/appid/1",URL2,module,interface,hashString];
    
    NSDictionary *parameter = @{@"time":timeString,@"mid":[UserMessage sharedUserMessage].userMid};
    
    //POST请求
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:urlString parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        
        if ([[dic objectForKey:@"succ"] isEqualToNumber:@1]) {
            
            downStudycard = [NSString stringWithFormat:@"%@",[dic objectForKey:@"info"]];
        }else{
            downStudycard=@"0";
        }
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        downStudycard=@"0";
    }];
    
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}



@end

